import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'
import $axios from '../tools/axios'

const basepath = '/station'
export const useQueryStore = defineStore('query', {
  state: () => {
    return {
      formData: {
        fromnm: '',
        tonm: '',
        date: '',
        type: []
      },
      fromstation: [],
      tostation: [],
      TableData: []
    }
  },

  actions: {
    getCurrentDate() {
      var now = new Date()
      var year = now.getFullYear()
      var month = now.getMonth() + 1
      var day = now.getDate()

      month = month < 10 ? Number('0' + month) : month
      day = day < 10 ? Number('0' + day) : day
      //在actions中使用this.state中的属性
      this.formData.date = year + '-' + month + '-' + day
    },

    query() {
      const path = basepath + '/query/' + this.formData.fromnm
      $axios.get(path).then(
        (response) => {
          if (response.data.code === 200) {
            this.fromstation = response.data.data
          } else {
            ElMessage.error('查询出发站失败！')
          }
        },
        (error) => {
          console.log('错误', error.message)
        }
      )

      const path1 = basepath + '/query/' + this.formData.tonm
      $axios.get(path1).then(
        (response) => {
          if (response.data.code === 200) {
            this.tostation = response.data.data
          } else {
            ElMessage.error('查询终点站失败！')
          }
        },
        (error) => {
          console.log('错误', error.message)
        }
      )

      const path2 =
        '/schedule/query?fromCity=' + this.formData.fromnm + '&towardCity=' + this.formData.tonm

      $axios.post(path2).then(
        (response) => {
          if (response.data.code === 200) {
            this.TableData = response.data.data

            //遍历车次信息
            this.TableData.forEach((element) => {
              const path3 = '/ticket/query/?fromSt=' + element.fromnm + '&toSt=' + element.tonm
              let date = ''
              if (typeof this.formData.date == 'string') {
                date = '0' + this.formData.date.substring(5, 9)
              } else {
                let y = this.formData.date.getFullYear()
                let m = this.formData.date.getMonth() + 1
                m = m < 10 ? '0' + m : m
                let d = this.formData.date.getDate()
                d = d < 10 ? '0' + d : d
                date = (y + '-' + m + '-' + d).substring(5, 10)
              }

              //查询商务座余票
              $axios
                .post(path3, {
                  trainno: element.trainno,
                  date: date,
                  carriage: '01'
                })
                .then(
                  (response) => {
                    if (response.data.code === 200) {
                      element.bussiness = response.data.data.length
                    } else {
                      ElMessage.error('查询商务座余票数量失败！')
                    }
                  },
                  (error) => {
                    console.log('错误', error.message)
                  }
                )

              //查询一等座余票
              $axios
                .post(path3, {
                  trainno: element.trainno,
                  date: date,
                  carriage: '02'
                })
                .then(
                  (response) => {
                    if (response.data.code === 200) {
                      element.one = response.data.data.length
                    } else {
                      ElMessage.error('查询一等座余票数量失败！')
                    }
                  },
                  (error) => {
                    console.log('错误', error.message)
                  }
                )

              //查询二等座余票
              $axios
                .post(path3, {
                  trainno: element.trainno,
                  date: date,
                  carriage: '03'
                })
                .then(
                  (response) => {
                    if (response.data.code === 200) {
                      element.two = response.data.data.length
                    } else {
                      ElMessage.error('查询二等座余票数量失败！')
                    }
                  },
                  (error) => {
                    console.log('错误', error.message)
                  }
                )

              var hours = parseInt(element.totime.split(':')[0])
              var mins = parseInt(element.totime.split(':')[1])
              mins -= element.running
              while (mins < 0) {
                hours--
                mins += 60
              }
              element.totime =
                hours.toString().padStart(2, '0') + ':' + mins.toString().padStart(2, '0')

              // 将时间字符串转换为分钟数
              var time1Minutes =
                parseInt(element.totime.split(':')[0]) * 60 + parseInt(element.totime.split(':')[1])
              var time2Minutes =
                parseInt(element.ltime.split(':')[0]) * 60 + parseInt(element.ltime.split(':')[1])

              // 计算时间差并将其转换为分钟
              var timeDifference = Math.abs(time2Minutes - time1Minutes)

              element.running = timeDifference+'分钟'

              element.seniorSoft = '-'
              element.softSleep = '-'
              element.hardSleep = '-'
              element.hardSit = '-'

              //查询该车次票价
              const path4 = 'schedule/calprice'
              $axios
                .post(path4, {
                  trainno: element.trainno
                })
                .then(
                  (response) => {
                    if (response.data.code === 200) {
             

                      let start = 0
                      let end = 0
                      response.data.data.forEach((elt, index) => {
                        if (elt.fromnm == element.fromnm) {
                          start = index
                        }
                        if (elt.tonm == element.tonm) {
                          end = index
                        }
                      })
               
                      let sum = 0
                      for (let i = start; i <= end; i++) {
                        sum += response.data.data[i].price
                      }

                      element.money = [
                        {
                          business: '￥' + (sum * 1.5).toFixed(1),
                          one: '￥' + sum.toFixed(1),
                          two: '￥' + (sum * 0.8).toFixed(1),
                          seniorSoft: '-',
                          softSleep: '-',
                          hardSleep: '-',
                          hardSit: '-'
                        }
                      ]
                    } else {
                      ElMessage.error('查询票价失败！')
                    }
                  },
                  (error) => {
                    console.log('错误', error.message)
                  }
                )
            })
          } else {
            ElMessage.error('查询车次信息失败！')
          }
        },
        (error) => {
          console.log('错误', error.message)
        }
      )
    }
  }
})
